package com.tj.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

@SuppressWarnings("unchecked")
public class CommonUtil {
    public static HashMap<String, String> loadPropertyFile(InputStream ins) throws IOException {
        Properties p = new Properties();
        HashMap<String, String> r = new HashMap<String, String>();
        try {
            p.load(ins);
            Set keys = p.keySet();
            for (Object o : keys) {
                String k = ((String) o).toLowerCase();
                String v = (String) p.get(o);
                r.put(k, v);
            }
        } finally {
            closeStream(ins);
        }
        return r;
    }

    public static boolean loadStaticPropertyFromFile(Class clazz, InputStream ins) throws IOException {
        if (ins == null) {
            System.err.println("Can not access input stream, it's null.");
            return false;
        }
        Properties p = new Properties();
        Field[] fields = clazz.getDeclaredFields();
        HashMap<String, Field> fieldMap = new HashMap<String, Field>();
        for (int i = 0, len = fields.length; i < len; i++) {
            Field field = fields[i];
            if (Modifier.isStatic(field.getModifiers())) {
                fieldMap.put(field.getName().toLowerCase(), field);
            }
        }
        if (fieldMap.size() == 0) {
            return true;
        }
        try {
            p.load(ins);
            Set keys = p.keySet();
            for (Object o : keys) {
                String k = ((String) o).toLowerCase();
                String v = (String) p.get(o);
                Field field = fieldMap.get(k);
                if (field != null) {
                    try {
                        setFieldValue(field, v);
                    } catch (IllegalAccessException e) {
                        System.err.println("can not set field for" + field.getName());
                    }
                }
            }
        } finally {
            closeStream(ins);
        }
        return true;
    }

    public static String dumpStaticPropertyFromClass(Class clazz) {
        Field[] fields = clazz.getDeclaredFields();
        StringBuffer buf = new StringBuffer();
        for (int i = 0, len = fields.length; i < len; i++) {
            Field field = fields[i];
            if (Modifier.isStatic(field.getModifiers())) {
                try {
                    Object o = field.get(null);
                    if (o != null) {
                        buf.append(field.getName());
                        buf.append("  :  ");
                        if (o instanceof Object[]) {
                            Object[] oa = (Object[]) o;
                            if (oa.length != 0) {
                                for (Object n : oa) {
                                    if (n != null) {
                                        buf.append(n.toString());
                                        buf.append(',');
                                    }
                                }
                                if (buf.charAt(buf.length() - 1) == ',')
                                    buf.deleteCharAt(buf.length() - 1);
                            }
                        } else {
                            buf.append(o.toString());
                        }
                        buf.append('\n');
                    }
                } catch (IllegalAccessException e) {
                }
            }
        }
        return buf.toString();
    }

    public static void setFieldValue(Field field, String value) throws IllegalAccessException {
        Class clazz = field.getType();
        if (clazz.equals(Integer.TYPE) || clazz.equals(Integer.class)) {
            field.set(null, Integer.parseInt(value));
        } else if (clazz.equals(Long.class) || clazz.equals(Long.TYPE)) {
            field.set(null, Long.parseLong(value));
        } else if (clazz.equals(String.class)) {
            field.set(null, value);
        } else if (clazz.equals(Boolean.class) || clazz.equals(Boolean.TYPE)) {
            field.set(null, Boolean.parseBoolean(value));
        } else {
            throw new UnsupportedOperationException();
        }
    }

    public static void closeStream(Object o) {
        try {
            if (o == null) {
                return;
            } else if (o instanceof InputStream) {
                ((InputStream) o).close();
            } else if (o instanceof OutputStream) {
                ((OutputStream) o).close();
            } else if (o instanceof Reader) {
                ((Reader) o).close();
            } else if (o instanceof Writer) {
                ((Writer) o).close();
            }
        } catch (Exception e) {
            System.err.println("Error closing stream");
            e.printStackTrace();
        }

    }

    public static String getFileSuffix(String name) {
        if (name == null)
            return "";
        int i = name.lastIndexOf('.');
        if (i == -1)
            return "";
        return new String(name.substring(i + 1));
    }

    public static Date msecefore(long msec) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(cal.getTime().getTime() - msec);
        return cal.getTime();
    }

    public static Date hoursBefore(int hours) {
        return msecefore(hours * 3600000);
    }

    public static Date daysBefore(int days) {
        return msecefore(86400000 * days);
    }

    public static void main(String[] args) {
        System.out.println(daysBefore(1));
    }

}
